# 三个同事 同时用一个打印机打印内容.
# 三个进程模拟三个同事, 输出平台模拟打印机.

# 版本一:
# from multiprocessing import Process
# import time
# import random
# import os
#
# def task1():
#     print(f'{os.getpid()}开始打印了')
#     time.sleep(random.randint(1,3))
#     print(f'{os.getpid()}打印结束了')
#
# def task2():
#     print(f'{os.getpid()}开始打印了')
#     time.sleep(random.randint(1,3))
#     print(f'{os.getpid()}打印结束了')
#
# def task3():
#     print(f'{os.getpid()}开始打印了')
#     time.sleep(random.randint(1,3))
#     print(f'{os.getpid()}打印结束了')
#
# if __name__ == '__main__':
#
#     p1 = Process(target=task1)
#     p2 = Process(target=task2)
#     p3 = Process(target=task3)
#
#     p1.start()
#     p2.start()
#     p3.start()

# 现在是所有的进程都并发的抢占打印机,
# 并发是以效率优先的,但是目前我们的需求: 顺序优先.
# 多个进程共强一个资源时, 要保证顺序优先: 串行,一个一个来.


# 版本二:


# from multiprocessing import Process
# import time
# import random
# import os
#
# def task1(p):
#     print(f'{p}开始打印了')
#     time.sleep(random.randint(1,3))
#     print(f'{p}打印结束了')
#
# def task2(p):
#     print(f'{p}开始打印了')
#     time.sleep(random.randint(1,3))
#     print(f'{p}打印结束了')
#
# def task3(p):
#     print(f'{p}开始打印了')
#     time.sleep(random.randint(1,3))
#     print(f'{p}打印结束了')
#
# if __name__ == '__main__':
#
#     p1 = Process(target=task1,args=('p1',))
#     p2 = Process(target=task2,args=('p2',))
#     p3 = Process(target=task3,args=('p3',))
#
#     p2.start()
#     p2.join()
#     p1.start()
#     p1.join()
#     p3.start()
#     p3.join()

# 我们利用join 解决串行的问题,保证了顺序优先,但是这个谁先谁后是固定的.
# 这样不合理. 你在争抢同一个资源的时候,应该是先到先得,保证公平.


# 版本3:

from multiprocessing import Process
from multiprocessing import Lock
import time
import random
import os

def task1(p,lock):
    '''
    一把锁不能连续锁两次
    lock.acquire()
    lock.acquire()
    lock.release()
    lock.release()
    '''
    lock.acquire()
    print(f'{p}开始打印了')
    time.sleep(random.randint(1,3))
    print(f'{p}打印结束了')
    lock.release()

def task2(p,lock):
    lock.acquire()
    print(f'{p}开始打印了')
    time.sleep(random.randint(1,3))
    print(f'{p}打印结束了')
    lock.release()

def task3(p,lock):
    lock.acquire()
    print(f'{p}开始打印了')
    time.sleep(random.randint(1,3))
    print(f'{p}打印结束了')
    lock.release()

if __name__ == '__main__':

    mutex = Lock()
    p1 = Process(target=task1,args=('p1',mutex))
    p2 = Process(target=task2,args=('p2',mutex))
    p3 = Process(target=task3,args=('p3',mutex))

    p2.start()
    p1.start()
    p3.start()